<template>
  <div class="h-full flex-col">
    <SearchForm @handle-reset="resetParams" @handle-search="getList">
      <el-form :model="searchForm" inline>
        <el-form-item label="처리상태">
          <el-select v-model="searchForm.status" placeholder="전체" clearable class="w-220px" @change="getList">
            <el-option label="진행중" :value="0" />
            <el-option label="출금승인" :value="1" />
            <el-option label="출금거절" :value="2" />
            <el-option label="승인취소-성공" :value="3" />
            <el-option label="승인취소-실패" :value="4" />
            <el-option label="전체기록" :value="-1" />
          </el-select>
        </el-form-item>
        <el-form-item label="검색조건">
          <el-input v-model="myPlayerLevel" placeholder="회원등급" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.agent_player_name" placeholder="로얄회원ID" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.agent_player_id" placeholder="로얄회원번호" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.phone_number" placeholder="전화번호" />
        </el-form-item>
      </el-form>
    </SearchForm>

    <el-row v-if="searchForm.status === 0" :gutter="20" style="margin-bottom: 10px">
      <el-col :span="4">
        <el-button type="primary" @click="widthdrawConfirmAllHandle">일괄승인</el-button>
        <el-button type="warning" @click="widthdrawDeleteAllHandle">일괄반려</el-button>
      </el-col>
    </el-row>

    <div class="page-card h-full m-table-position" v-loading="loading">
      <div class="m-withdraw-amount-sum">
        <span>총 출금신청:</span>
        <el-tag :type="withdrawAmountSum > 0 ? 'danger' : 'success'">
          {{ formatNumber(withdrawAmountSum) }}
        </el-tag>
      </div>

      <MyTable :tableData="tableData" :tableColumn="tableColumn" v-slot="sp">
        <MyDragTable :columnList="columnList" :tableData="tableData" :isSlotSelect="true"
          @handleSelectionChange="handleSelectionChange" @sortChangeHandle="sortChangeHandle" :sp="sp">
          <template v-if="searchForm.status === 0" #slotCheckBox>
            <el-table-column type="selection" width="55" />
          </template>
          <template #slotOperation>
            <el-table-column v-if="searchForm.status === 0" label="편집" fixed="right" width="140" align="center">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="withdrawEditHandle(row)">승인</el-button>
                <el-button type="warning" size="small" @click="withdrawDeleteHandle(row)">반려</el-button>
              </template>
            </el-table-column>

            <el-table-column v-if="searchForm.status === 1" label="편집" fixed="right" width="80" align="center">
              <template #default="{ row }">
                <el-button type="warning" size="small" @click="withdrawRevokeHandle(row)">승인취소</el-button>
              </template>
            </el-table-column>
          </template>
        </MyDragTable>

        <Pagination :pageable="page" :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange" />
      </MyTable>

      <el-drawer v-model="userMyRechargeDrawer" :title="userMyRechargeDrawerTitle" direction="rtl" size="1500">
        <el-table :data="userMyRechargeDrawerList" style="width: 100%">
          <el-table-column label="입금예금주" prop="depositor_name" align="center" width="150" />
          <el-table-column label="입금금액" align="center" width="150">
            <template #default="{ row }">
              <el-tag>
                {{ formatNumber(row.amount) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="출금시-누적배팅금" align="center" width="150">
            <template #default="{ row }">
              <el-tag type="danger">
                {{ formatNumber(row.bet_amount) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="입금보너스" prop="amount_bonus" align="center" />
          <el-table-column label="입금시잔액" prop="balance" align="center" />
          <el-table-column label="메모" prop="note" align="center" width="400" />
          <el-table-column label="처리시간" align="center" width="200">
            <template #default="{ row }">
              {{ timestampToSeoul(row.finish_ts * 1000, 'Y-m-d H:i:s', 1) }}
            </template>
          </el-table-column>
          <el-table-column label="처리상태" align="center">
            <template #default="{ row }">
              {{ row.status == 1 ? '입금승인' : '-' }}
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useTable } from '@/hooks/useTable';
import {
  withdrawListApi,
  withdrawApproveApi,
  withdrawRejectApi,
  withdrawRevokeApi
} from '@/api/financial/index';
import { rechargeListApi } from '@/api/financial/index';
import { formatNumber, dataTimeRangeCurTwo, formatDate, timestampToSeoul } from '@/utils/util';
import { ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { selectGuidMapGet } from '@/utils/gameUtil';
import MyTable from '@/components/MyTable';
import { useMyTip } from '@/hooks/useMyTip';
import MyDragTable from '@/components/MyDragTable';
import columnListConfig from './columnList.ts';

const mySortArr: any = ref([])

const sortChangeHandle = ({ column, prop, order }) => {
  mySortArr.value = [prop, order];
}

const columnList = ref(columnListConfig);

const { operationSuccessMsg } = useMyTip();

const tableColumn = ref([
  'ID',
  '로얄회원번호',
  '로얄회원ID',
  '휴대폰번호',
  '등급번호',
  '등급명',
  '신청금액',
  '잔액',
  '출금시-누적배팅금',
  '최근출금자명',
  '이벤트출금&쿠폰',
  '출금은행',
  '출금계좌',
  '메모',
  '신청시간',
  '사이트구분',
  '게임사',
  '처리시간',
  '처리상태'
]);

const statusMap = {
  '0': '진행중',
  '1': '출금승인',
  '2': '출금거절',
  '3': '승인취소-성공',
  '4': '승인취소-실패',
  '-1': '전체기록'
};

const userMyRechargeDrawer = ref(false);
const userMyRechargeDrawerTitle = ref('');
const userMyRechargeDrawerList = ref([]);

const userMyRechargeList = (row: any) => {
  userMyRechargeDrawerTitle.value = `회원계정: ${row.agent_player_name}`;
  userMyRechargeDrawer.value = true;
  rechargeListApi({
    agent_player_id: row.agent_player_id,
    agent_player_name: '',
    page: 1,
    page_size: 10,
    phone_number: '',
    player_level: '',
    status: '-1'
  }).then((res: any) => {
    console.log('userMyRechargeList----');
    console.log(res);
    userMyRechargeDrawerList.value = res.data.data.orders;
  });
};

const { t } = useI18n();

const withdrawEditHandle = (row: any) => {

  ElMessageBox.confirm(
    `${row.agent_player_name}등급 회원입니다${row.amount.value}원 출금|승인|하시겠습니까?`,
    t('common.mMessageTitle'),
    {
      confirmButtonText: t('common.mConfirmBtn'),
      cancelButtonText: t('common.mCancelBtn'),
      draggable: true
    }
  ).then(() => {
    withdrawApproveApi({ guid: row.guid }).then(({ status }) => {
      tableDataFilter(row.guid);
      if (status == 0) {
        operationSuccessMsg();
      }
    });
  });
};

const withdrawDeleteHandle = (row: any) => {
  ElMessageBox.confirm(`출금을 거절 하시겠습니까?`, t('common.mMessageTitle'), {
    confirmButtonText: t('common.mConfirmBtn'),
    cancelButtonText: t('common.mCancelBtn'),
    draggable: true
  }).then(() => {
    withdrawRejectApi({ guid: row.guid }).then(({ status }) => {
      tableDataFilter(row.guid);
      if (status == 0) {
        operationSuccessMsg();
      }
    });
  });
};

const withdrawRevokeHandle = (row: any) => {
  ElMessageBox.confirm(`출금 승인취소 하시겠습니까?`, t('common.mMessageTitle'), {
    confirmButtonText: t('common.mConfirmBtn'),
    cancelButtonText: t('common.mCancelBtn'),
    draggable: true
  }).then(() => {
    withdrawRevokeApi({ guid: row.guid }).then(({ status }) => {
      operationSuccessMsg();
      if (status == 0) {
        tableDataFilter(row.guid);
      }
    });
  });
};

const widthdrawConfirmAllHandle = () => {
  const guidArr = selectGuidMapGet(multipleSelection.value);
  const betAmountArr = selectGuidMapGet(multipleSelection.value, 'amount');
  const betAmountAll = betAmountArr.reduce((prev: number, item: number) => {
    const betAmount = Number(item.value.split(',').join(''));
    return prev + betAmount;
  }, 0);

  const levelArr = selectGuidMapGet(multipleSelection.value, 'player_level_name');
  const levelHtml = levelArr.reduce((prev: any, item: any) => {
    return prev + `<div>${item}</div>`;
  }, '');

  ElMessageBox.confirm(
    `
            <div>
                ${levelHtml}
                <div>총금액:<span class="m-color-red">${formatNumber(betAmountAll)}</span></div>
                <div>총건수:<span class="m-color-red">${formatNumber(guidArr.length)}</span></div>
                <div>일괄 출금승인 하시겠습니까?</div>
            </div>
        `,
    t('common.mMessageTitle'),
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: t('common.mConfirmBtn'),
      cancelButtonText: t('common.mCancelBtn'),
      draggable: true
    }
  ).then(() => {
    let myStatus = 0;
    guidArr.map(async (guid: any) => {
      const { status } = withdrawApproveApi({ guid });
      if (status != 0) {
        myStatus = status;
      }
    });
    operationSuccessMsg(myStatus);
    guidArr.map((guid: any) => {
      tableDataFilter(guid)
    })
  });
};

const widthdrawDeleteAllHandle = () => {
  const guidArr = selectGuidMapGet(multipleSelection.value);
  ElMessageBox.confirm('일괄 출금반려 하시겠습니까?', t('common.mMessageTitle'), {
    dangerouslyUseHTMLString: true,
    confirmButtonText: t('common.mConfirmBtn'),
    cancelButtonText: t('common.mCancelBtn'),
    draggable: true
  }).then(() => {
    let myStatus = 0;
    guidArr.map(async (guid: any) => {
      const { status } = withdrawRejectApi({ guid });
      if (status != 0) {
        myStatus = status;
      }
    });
    operationSuccessMsg(myStatus);
    guidArr.map((guid: any) => {
      tableDataFilter(guid)
    })
  });
};

const dateTimeRange = dataTimeRangeCurTwo();

const searchForm: any = reactive({
  agent_player_id: '',
  agent_player_name: '',
  phone_number: '',
  player_level: [],
  status: 0
});

const myPlayerLevel = ref('');

watch(myPlayerLevel, (cur: string) => {
  const levelArr = cur.split(',').filter((item) => item);
  searchForm.player_level = levelArr;
});

const multipleSelection = ref([]);

const handleSelectionChange = (val: []) => {
  multipleSelection.value = val;
};

const dataTimeRange: any = ref([]);

onMounted(() => {
  dataTimeRange.value = dateTimeRange.map((item: any) => new Date(item * 1000));
});

const withdrawAmountSum = ref(0);

const dataCallBack = (data: any) => {
  const _data = data.data;

  let _withdrawAmountSum = 0;

  let list = _data.orders.map((item: any) => {
    _withdrawAmountSum += item.amount;

    item.amount = {
      value: formatNumber(item.amount),
      type: item.amount > 0 ? 'danger' : 'success',
      handle: userMyRechargeList
    };

    item.balance = {
      value: formatNumber(item.balance),
      type: item.balance > 0 ? 'danger' : 'success'
    };

    item.create_ts = timestampToSeoul(item.create_ts * 1000, 'Y-m-d H:i:s', 1);

    if (Number(item.finish_ts) === 0) {
      item.finish_ts = '';
    } else {
      item.finish_ts = timestampToSeoul(item.finish_ts * 1000, 'Y-m-d H:i:s', 1);
    }

    item.status = statusMap[item.status.toString()];
    return item;
  });

  if (mySortArr.value.length > 0) {

    const myProp = mySortArr.value[0]
    const myOrder = mySortArr.value[1]

    if (myProp == 'create_ts') {
      list = list.sort((a: any, b: any) => {
        if (myOrder == 'ascending') {
          return +new Date(a[myProp]) - +new Date(b[myProp]);
        }
        return +new Date(b[myProp]) - +new Date(a[myProp]);
      });
    }
  }

  withdrawAmountSum.value = _withdrawAmountSum;

  return {
    list,
    total: _data.total_count
  };
};

const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange, tableDataFilter } =
  useTable({
    apiFn: withdrawListApi,
    params: searchForm,
    callback: dataCallBack,
    reload: 60
  });
</script>

<style lang="scss" scoped>
.m-table-position {
  position: relative;
}

.m-withdraw-amount-sum {
  position: absolute;
  bottom: 0;
  left: 1.25rem;
  height: 50px;
  width: 300px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.m-withdraw-amount-sum span {
  margin-right: 10px;
}
</style>
